package com.ruoyi.device.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.device.domain.DeviceInfo;
import com.ruoyi.device.service.IDeviceInfoService;
import com.ruoyi.device.service.IDeviceSyncService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 设备信息Controller
 * 
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/device")
public class DeviceInfoController extends BaseController
{
    @Autowired
    private IDeviceInfoService deviceInfoService;

    @Autowired
    private IDeviceSyncService deviceSyncService;

    /**
     * 查询设备信息列表
     */
    @RequiresPermissions("device:device:list")
    @GetMapping("/list")
    public TableDataInfo list(DeviceInfo deviceInfo)
    {
        startPage();
        List<DeviceInfo> list = deviceInfoService.selectDeviceInfoList(deviceInfo);
        return getDataTable(list);
    }

    /**
     * 导出设备信息列表
     */
    @RequiresPermissions("device:device:export")
    @Log(title = "设备信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DeviceInfo deviceInfo)
    {
        List<DeviceInfo> list = deviceInfoService.selectDeviceInfoList(deviceInfo);
        ExcelUtil<DeviceInfo> util = new ExcelUtil<DeviceInfo>(DeviceInfo.class);
        util.exportExcel(response, list, "设备信息数据");
    }

    /**
     * 获取设备信息详细信息
     */
    @RequiresPermissions("device:device:query")
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") String deviceId)
    {
        return success(deviceInfoService.selectDeviceInfoByDeviceId(deviceId));
    }

    /**
     * 新增设备信息
     */
    @RequiresPermissions("device:device:add")
    @Log(title = "设备信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DeviceInfo deviceInfo)
    {
        return toAjax(deviceInfoService.insertDeviceInfo(deviceInfo));
    }

    /**
     * 修改设备信息
     */
    @RequiresPermissions("device:device:edit")
    @Log(title = "设备信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DeviceInfo deviceInfo)
    {
        return toAjax(deviceInfoService.updateDeviceInfo(deviceInfo));
    }

    /**
     * 删除设备信息
     */
    @RequiresPermissions("device:device:remove")
    @Log(title = "设备信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{deviceIds}")
    public AjaxResult remove(@PathVariable String[] deviceIds)
    {
        return toAjax(deviceInfoService.deleteDeviceInfoByDeviceIds(deviceIds));
    }

    /**
     * 生成WiFi二维码
     */
    @RequiresPermissions("device:device:qrcode")
    @PostMapping("/qrcode/{deviceId}")
    public AjaxResult generateQrCode(@PathVariable String deviceId)
    {
        String qrCodeBase64 = deviceInfoService.generateQrCode(deviceId);
        return success().put("data", "data:image/png;base64," + qrCodeBase64);
    }

    /**
     * 获取设备WiFi信息（供小程序使用）
     */
    @GetMapping("/wifi/{deviceId}")
    public AjaxResult getDeviceWifiInfo(@PathVariable String deviceId)
    {
        DeviceInfo device = deviceInfoService.selectDeviceInfoByDeviceId(deviceId);
        if (device == null)
        {
            return error("设备不存在");
        }
        
        if (device.getWifiEnabled() == null || device.getWifiEnabled() == 0)
        {
            return error("设备WiFi功能未启用");
        }

        // 构建WiFi信息响应
        Map<String, Object> wifiInfo = new HashMap<>();
        wifiInfo.put("ssid", device.getWifiSsid());
        wifiInfo.put("password", device.getWifiPassword());
        wifiInfo.put("securityType", device.getWifiSecurityType());
        wifiInfo.put("frequency", device.getWifiFrequency());
        wifiInfo.put("signalStrength", device.getWifiSignalStrength());
        wifiInfo.put("isSecure", device.getWifiSecurityType() != null && device.getWifiSecurityType() > 0);
        
        // 设备基本信息
        wifiInfo.put("deviceId", device.getDeviceId());
        wifiInfo.put("deviceName", device.getDeviceName());
        wifiInfo.put("locationName", device.getLocationName());
        
        return success(wifiInfo);
    }

    /**
     * 获取设备状态
     */
    @RequiresPermissions("device:device:query")
    @GetMapping("/status/{deviceId}")
    public AjaxResult getDeviceStatus(@PathVariable String deviceId)
    {
        DeviceInfo deviceInfo = deviceInfoService.selectDeviceInfoByDeviceId(deviceId);
        if (deviceInfo == null) {
            return error("设备不存在");
        }
        return success(deviceInfo.getStatus());
    }

    /**
     * 更新设备心跳
     */
    @PostMapping("/heartbeat/{deviceId}")
    public AjaxResult updateHeartbeat(@PathVariable String deviceId)
    {
        return toAjax(deviceInfoService.updateDeviceHeartbeat(deviceId));
    }

    /**
     * 获取设备统计信息
     */
    @RequiresPermissions("device:device:list")
    @GetMapping("/statistics")
    public AjaxResult getStatistics()
    {
        return success(deviceInfoService.getDeviceStatistics());
    }

    /**
     * 同步所有设备信息（供定时任务调用）
     */
    @PostMapping("/sync/all")
    public AjaxResult syncAllDevices()
    {
        try {
            deviceSyncService.syncAllDevices();
            return success("设备同步任务执行成功");
        } catch (Exception e) {
            return error("设备同步任务执行失败: " + e.getMessage());
        }
    }

    /**
     * 同步单个设备信息（供定时任务调用）
     */
    @PostMapping("/sync/{deviceId}")
    public AjaxResult syncDeviceInfo(@PathVariable String deviceId)
    {
        try {
            deviceSyncService.syncDeviceInfo(deviceId);
            return success("设备同步成功");
        } catch (Exception e) {
            return error("设备同步失败: " + e.getMessage());
        }
    }
} 